package org.xxpay.pay.channel.tfpay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.pay.ctrl.common.BaseController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @Description: 支付宝转账通道跳转
 * @author pangxiaoyu
 * @date 2020-04-26
 */
@Controller
public class TfpayController extends BaseController {

	private static final MyLog _log = MyLog.getLog(TfpayController.class);

	/**
	 * 转到前端收银台界面
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/channel/"+TfpayConfig.CHANNEL_NAME+"/{param}")
	public String toPay(HttpServletRequest request, ModelMap model, @PathVariable("param")String param) {
		String paramStr = new String(MyBase64.decode(param));
		JSONObject paramObj = JSONObject.parseObject(paramStr);
		String account = getString(paramObj, "account");
		String payOrderId = getString(paramObj, "payOrderId");
		String accountName = getString(paramObj, "accountName");
		String amount = getString(paramObj, "amount");
		DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
		// 订单创建时间与当前时间差值(此处使用db计算，为了避免服务器和db时间有差异)
		Long expireTime = commonService.payOrderService.getOrderTimeLeft(payOrderId, TfpayConfig.PAY_ORDER_TIME_OUT);
		if(expireTime == null || expireTime < 0) expireTime = 0l;
		model.put("amount", AmountUtil.convertCent2Dollar(amount));
		model.put("tradeNo", payOrderId);
		model.put("memo", payOrderId);
		model.put("expireTime", expireTime);
		model.put("alipayName", accountName);
		model.put("alipayAccount", account);
		//ws地址： ws://localhost:8088/ws/payOrder/P11100001/20180010101
		String payDomain = dbConfig.getConfig4PayUrl().replace("http://", "").replace("https://", "").replace("/api",""); //去掉http协议
		String wsProtocol = dbConfig.getConfig4PayUrl().startsWith("http://") ? "ws://" : "wss://"; //ws协议
		model.put("wsAddress", wsProtocol + payDomain + "/ws/payOrder/" + payOrderId + "/" + new Date().getTime());
		return "payment/"+TfpayConfig.CHANNEL_NAME+"/alipay_tf";
	}

}
